package io.renren.modules.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ma
 * @date 2020/5/8 10:09
 */

@RestController
@RequestMapping(value = "/api/v1/test")
@Slf4j
@Api(tags = "APP测试模块")
public class Test {

    private static String key = "8bce714bac4557cc853f5d4af40614b9";


    /**
     * 阿里云api 根据经纬度获取地址
     * @param log
     * @param lat
     * @return
     */
    @PostMapping(value = "/test")
    @ApiOperation("根据经纬度获取地址")
    public R getAdd(String log, String lat) {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&location=").append(log).append(",").append(lat);
        String res = sendPost("http://restapi.amap.com/v3/geocode/regeo", s.toString());


        JSONObject jsonobject = (JSONObject) JSON.parse(res);
        JSONObject jsonObject1 = (JSONObject) JSONObject.parse(jsonobject.get("regeocode").toString());
        String add = jsonObject1.get("formatted_address").toString();
        return R.ok();

    }


    /**
     * 高德api 根据地址获取经纬度
     *
     * @param name
     * @return
     */
    @PostMapping(value = "/test2")
    @ApiOperation("根据地址获取经纬度")
    public R getLatAndLogByName(String name) {
        StringBuffer s = new StringBuffer();
        s.append("key=" + key + "&address=" + name);
        String res = sendPost("http://restapi.amap.com/v3/geocode/geo", s.toString());

        JSONObject jsonObject = (JSONObject) JSON.parse(res);
        JSONArray jsonArray = (JSONArray) JSONArray.parse(jsonObject.getString("geocodes"));
        JSONObject location = (JSONObject) jsonArray.get(0);
        String add = location.get("location").toString();
        return R.ok();
    }


    /**
     * 高德api 根据地址获取经纬度
     *
     * @param
     * @return
     */
    @PostMapping(value = "/test3")
    @ApiOperation("根据经纬度获取地址")
    public R getAddByAMAP(String log, String lat) {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&location=").append(log).append(",").append(lat);
        String res = sendPost("http://restapi.amap.com/v3/geocode/regeo", s.toString());

        JSONObject jsonObject = (JSONObject) JSON.parse(res);
        JSONObject jsonObject1 = (JSONObject) JSONObject.parse(jsonObject.get("regeocode").toString());
        String add = jsonObject1.get("formatted_address").toString();
        return R.ok();
    }


    /**
     * 高德api 关键字模糊查询
     *
     * @param keyWord
     * @param city
     * @return
     */
    @PostMapping(value = "/test4")
    @ApiOperation("关键字模糊查询")
    public R getKeywordsAddByLbs(String keyWord, String city) {
        StringBuffer s = new StringBuffer();
        s.append("key=" + key + "&keywords=");
        if (keyWord.contains(" ")) {
            String[] str = keyWord.split(" ");
            for (int i = 0; i < str.length; i++) {
                if (i == 0) {
                    s.append(str[i]);
                } else {
                    s.append("+" + str[i]);
                }
            }
        } else {
            s.append(keyWord);
        }
        s.append("&city=" + city);
        s.append("offset=10&page=1");
        String around = sendPost("http://restapi.amap.com/v3/place/text", s.toString());

        return R.ok();
    }


    /**
     * 高德api 经纬度/关键字 附近地标建筑及地点查询
     *
     * @param log
     * @param lat
     * @param keyWord
     * @return
     */
    @PostMapping(value = "/test5")
    @ApiOperation("经纬度/关键字 附近地标建筑及地点查询")
    public R getAroundAddByLbs(String log, String lat, String keyWord) {
        String around = sendPost("http://restapi.amap.com/v3/place/around",
                "key=" + key + "&location=" + log + "," + lat + "&keywords=" + keyWord +
                        "&radius=2000&offset=10&page=1");


        JSONObject jsonObject = (JSONObject) JSON.parse(around);
        JSONArray jsonArray = (JSONArray) JSONArray.parse(jsonObject.getString("pois"));
      /*  JSONObject jsonObject1 = (JSONObject) JSONObject.parse(jsonObject.get("pois").toString());
        String add = jsonObject1.get("formatted_address").toString();
     */
        List<Object> list = new ArrayList<>();
        for (Object json : jsonArray) {
            // ShopInfo shopInfo = new ShopInfo();
            list.add(json);
        }


        return R.ok();
    }

    /**
     * 高德api 根据地址获取经纬度
     *
     * @param
     * @return
     */
    @GetMapping(value = "/test6")
    @ApiOperation("获取当前经纬度")
    public R getLotAndLat() {
        StringBuffer s = new StringBuffer();
        try {
            InetAddress ip4 = Inet4Address.getLocalHost();
            s.append("key=").append(key).append("&ip=").append(ip4.getHostAddress());
            String res = sendPost("https://restapi.amap.com/v3/ip", s.toString());
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }

       /* s.append("key=").append(key);
        String res = sendPost("https://restapi.amap.com/v3/ip", s.toString());*/
        return R.ok();
    }


    /**
     * 根据ip获取地址
     * @param
     * @return
     */
    public R getAddressByIp(){
        try {
       /*     String url = "https://restapi.amap.com/v3/ip";
            Map<String,Object> parameters = Maps.newHashMap();
            //ip=114.247.50.2&output=xml&key=<用户的key>
            parameters.put("ip",ip);
            parameters.put("key",key);*/
            StringBuffer s = new StringBuffer();
            InetAddress ip4 = Inet4Address.getLocalHost();
            s.append("key=").append(key).append("&ip=").append(ip4.getHostAddress());
            String res=  sendPost("https://restapi.amap.com/v3/ip",s.toString());
            if (null!=res) {
                log.info("getAddressByIp result={}",res);
                JSONObject resultObj = JSONObject.parseObject(res);
                String returnStr = resultObj.getString("province")+","+resultObj.getString("city");
                if(returnStr.contains("[],[]")){
                    return R.ok();
                }
                return R.ok();
            }
        } catch (Exception e) {
            log.error("getAddressByIp error={}",e);
        }
        return R.ok();
    }



    /*  */

    /**
     * 阿里云api 根据经纬度获取所在城市
     *
     * @param
     * @param
     * @return
     *//*
    @PostMapping(value = "/test1")
    @ApiOperation("根据经纬度获取所在城市")
    public ApiResponse<String> getCity(String log, String lat) {
        // log 大 lat 小
        // 参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
        String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat + "," + log + "&type=010";
        String res = "";
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

            String line;
            while ((line = in.readLine()) != null) {
                res += line + "\n";
            }
            in.close();

            JSONObject jsonobject = (JSONObject) JSON.parse(res);


            JSONArray jsonArray = (JSONArray) JSONArray.parse(jsonobject.getString("addrList"));
            JSONObject j_2 = (JSONObject) JSONObject.parse((String) jsonArray.get(0));
            String allAdd = j_2.getString("admName");
            String arr[] = allAdd.split(",");
            res = arr[1];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return apiResponse(res);
    }*/
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}


